<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>递归实现深拷贝</title>
</head>

<body>
    <script>
        const person = {
            name: '李四',
            age: 18,
            hobby: ['篮球', '游戏'],
            family: {
                dad: '老四',
                mom: '翠花'
            }
        }

        // 递归实现深拷贝
        const per = {}
        function deepCopy(newObject, oldObject) {
            for (const key in oldObject) {
                if (oldObject[key] instanceof Array) {
                    newObject[key] = []
                    deepCopy(newObject[key], oldObject[key])
                }
                else if (oldObject[key] instanceof Object) {
                    newObject[key] = {}
                    deepCopy(newObject[key], oldObject[key])
                }
                else {
                    newObject[key] = oldObject[key]
                }
            }
        }
        deepCopy(per, person)

        per.family.dad = '老六'
        per.hobby.push('rap')
        console.log(per); // {name: '李四', age: 18, hobby:['篮球', '游戏', 'rap'], family: {{dad: '老六', mom: '翠花'}}
        console.log(person); // {name: '李四', age: 18, hobby:['篮球', '游戏'], family: {{dad: '老四', mom: '翠花'}}
    </script>
</body>

</html>